const mongoose = require('mongoose');

async function fixAndSyncData() {
    try {
        await mongoose.connect('mongodb://127.0.0.1:27017/QWsystem');
        console.log('✅ 连接MongoDB成功\n');
        
        const DoctorData = require('./model/DoctorData');
        
        console.log('🔧 开始修复现有数据...\n');
        
        // 修复现有数据的科室字段
        const doctors = await DoctorData.find({});
        const departmentMap = {
            '傻呗森': '心血管内科',
            '彭楚杰': '神经内科', 
            '陈俊宇': '消化内科',
            '陆小果': '呼吸内科',
            '鲁洪伟': '内分泌科',
            '无敌暴龙战神': '急诊科'
        };
        
        for (let doctor of doctors) {
            const newDepartment = departmentMap[doctor.Doctorname] || '内科';
            
            console.log(`修复医生: ${doctor.Doctorname}`);
            console.log(`- 科室: "${doctor.Department}" → "${newDepartment}"`);
            
            await DoctorData.findByIdAndUpdate(doctor._id, {
                Department: newDepartment,
                updateTime: new Date()
            });
        }
        
        console.log('\n✅ 现有数据修复完成\n');
        
        // 创建一些新的示例医生数据
        console.log('➕ 创建新的示例医生数据...\n');
        
        const newDoctors = [
            {
                Doctorname: '张三',
                Doctorjob: '主任医师',
                Department: '心血管内科',
                Courtyardarea: '东院',
                status: '在职',
                phone: '13800138001',
                email: 'zhangsan@hospital.com',
                experience: 15,
                education: '博士',
                registrationFee: 100,
                Tags: ['心血管疾病', '高血压', '冠心病'],
                specialties: ['心脏介入手术', '心血管疾病诊治'],
                schedule: {
                    monday: true,
                    tuesday: true,
                    wednesday: false,
                    thursday: true,
                    friday: true,
                    saturday: false,
                    sunday: false
                },
                Doctorcontent: '心血管内科专家，擅长心脏介入手术和心血管疾病的诊治，从医15年，具有丰富的临床经验。'
            },
            {
                Doctorname: '李四',
                Doctorjob: '副主任医师',
                Department: '神经外科',
                Courtyardarea: '西院',
                status: '在职',
                phone: '13800138002',
                email: 'lisi@hospital.com',
                experience: 12,
                education: '硕士',
                registrationFee: 80,
                Tags: ['脑外科', '神经疾病', '脑肿瘤'],
                specialties: ['脑肿瘤切除', '神经外科手术'],
                schedule: {
                    monday: false,
                    tuesday: true,
                    wednesday: true,
                    thursday: true,
                    friday: false,
                    saturday: true,
                    sunday: false
                },
                Doctorcontent: '神经外科专家，专注于脑肿瘤和神经系统疾病的外科治疗，手术技术精湛。'
            },
            {
                Doctorname: '王五',
                Doctorjob: '主治医师',
                Department: '骨科',
                Courtyardarea: '总院',
                status: '在职',
                phone: '13800138003',
                email: 'wangwu@hospital.com',
                experience: 8,
                education: '本科',
                registrationFee: 60,
                Tags: ['骨折', '关节疾病', '运动损伤'],
                specialties: ['骨折治疗', '关节置换手术'],
                schedule: {
                    monday: true,
                    tuesday: false,
                    wednesday: true,
                    thursday: false,
                    friday: true,
                    saturday: true,
                    sunday: false
                },
                Doctorcontent: '骨科专家，擅长各种骨折治疗和关节疾病的诊治，对运动损伤有丰富经验。'
            }
        ];
        
        for (let doctorData of newDoctors) {
            // 检查是否已存在同名医生
            const existing = await DoctorData.findOne({ Doctorname: doctorData.Doctorname });
            if (!existing) {
                const newDoctor = await DoctorData.create(doctorData);
                console.log(`✅ 创建医生: ${newDoctor.Doctorname} - ${newDoctor.Department}`);
            } else {
                console.log(`⚠️ 医生 ${doctorData.Doctorname} 已存在，跳过创建`);
            }
        }
        
        // 显示最终结果
        console.log('\n📊 最终数据统计:');
        const finalDoctors = await DoctorData.find({});
        console.log(`总医生数量: ${finalDoctors.length}`);
        
        console.log('\n📋 所有医生列表:');
        finalDoctors.forEach((doc, index) => {
            console.log(`${index + 1}. ${doc.Doctorname} - ${doc.Department} - ${doc.Doctorjob} - ${doc.status}`);
        });
        
        // 创建默认头像文件（如果不存在）
        console.log('\n📁 检查并创建默认头像文件...');
        const fs = require('fs');
        const path = require('path');
        
        const staticDir = path.join(__dirname, 'static');
        if (!fs.existsSync(staticDir)) {
            fs.mkdirSync(staticDir, { recursive: true });
            console.log('✅ 创建static目录');
        }
        
        const defaultAvatarPath = path.join(staticDir, 'default-avatar.jpg');
        if (!fs.existsSync(defaultAvatarPath)) {
            // 创建一个简单的占位符文件
            fs.writeFileSync(defaultAvatarPath, 'placeholder');
            console.log('✅ 创建默认头像占位符');
        }
        
        mongoose.connection.close();
        console.log('\n🎉 数据修复和同步完成！');
        
    } catch (error) {
        console.error('❌ 修复失败:', error);
    }
}

fixAndSyncData(); 